package cn.shentianlan.service.impl;

import cn.shentianlan.dao.DeviceDao;
import cn.shentianlan.domain.Device;
import cn.shentianlan.domain.DeviceTable;
import cn.shentianlan.domain.Device;
import cn.shentianlan.domain.DeviceTable;
import cn.shentianlan.service.DeviceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {
    
    @Resource
    private DeviceDao deviceDao;
    
    @Override
    public DeviceTable showDevice(int start, int length, int draw, String searchValue) {

        List<Device> data = null;
        DeviceTable deviceTable = new DeviceTable();
        int totalPages = deviceDao.queryDeviceCount();
        //确保表数据不为空
        if (totalPages==0){
            Device device = new Device();
            device.setGd_dev_id("88888888");
            device.setGd_dev_name("样例");
            device.setGd_dev_factory("样例");
            device.setGd_dev_info("请新增一条数据后再删除此数据");
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
            device.setGd_dev_start(ft.format(new Date()));
            deviceDao.insertDevice(device);
        }
        if (searchValue!=null && searchValue.length()!=0){
            data = deviceDao.selectDeviceBySearch(searchValue,length,start);
            int recordsFiltered = deviceDao.queryDeviceCountBySearch(searchValue);
            deviceTable.setRecordsFiltered(recordsFiltered);
        }else {
            data = deviceDao.selectDevices(start,length);
            deviceTable.setRecordsFiltered(totalPages);
        }

        deviceTable.setData(data);
        deviceTable.setRecordsTotal(totalPages);
        deviceTable.setDraw(draw);

        return deviceTable;
    }

    @Override
    public boolean deleteDevice(String gd_dev_id) {
        try{
            deviceDao.deleteDeviceById(gd_dev_id);
            return true;
        }catch (Exception e){
            //将异常信息打印到控制台上
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void addDevice(Device device) {
        deviceDao.insertDevice(device);
    }

    @Override
    public void updateDevice(Device device) {
        deviceDao.updateDevice(device);
    }

    @Override
    public boolean getDeviceById(String gd_dev_id) {
        Device device = deviceDao.selectDeviceById(gd_dev_id);
        if (device!=null)
            return true;
        return false;
    }

    @Override
    public List<Device> getDevice() {
        List<Device> list = deviceDao.getDevice();
        return list;
    }



}
